import React from 'react';
import { Grid, Button, List, Toast, Modal, Icon, Popup, Flex } from 'antd-mobile';
import { connect } from 'dva';
import moment from 'moment';
import { Helmet } from 'react-helmet';
import _ from 'lodash';
import styles from './Appointment.less';
import Container from '../components/Base/Container';
import BranchSelectModal from '../components/Base/BranchSelectModal';
import TimeSelectModal from '../components/Base/TimeSelectModal';
import SaleManSelectModal from '../components/Base/SaleManSelectModal';
import * as appointmentService from '../services/appointmentService';
import classnames from 'classnames';
import { createForm } from "rc-form";
import { routerRedux } from "dva/router";
import { fetchBranchList } from "../services/statService";
const Item = List.Item;


// Branch 门店
// serviceId 服务


class Appointment extends React.Component {


  constructor(props) {
    super(props);

    this.state = {
      selectServiceId: null,
      branches: [],
      branchSelectModalVisiable: false,
      timeSelectModalVisiable: false,
      saleManSelectModalVisiable: false,
      branchSetting: null,
      selectBranch: null,
      selectTime: null,
      selectSaleMan: '',
    };
  }

  componentDidMount() {
  }

  renderItem = (item) => {
    return (<div
      className={
        classnames({
          [styles['grid-item']]: true,
          [styles['grid-item-highlight']]: item.isChecked,
        })
      }
    >
      <img src={item.icon} className={styles.image} alt="" />
      <div className={styles['grid-item-title']}>
        <span>{item.name}</span>
      </div>
    </div>);
  }


  handClickBranch = () => {
    this.setState({ branchSelectModalVisiable: true });
  }

  handClickTimes = () => {
    this.setState({ timeSelectModalVisiable: true });
  }

  handClickSaleMan = () => {
    this.setState({ saleManSelectModalVisiable: true });
  }

  handleServiceClick = (ele) => {
    _.each(this.props.services, (v) => {
      if (v._id === ele._id) {
        v.isChecked = true;
      } else {
        v.isChecked = false;
      }
    });
    this.setState({ selectServiceId: ele._id });

    // const saleManList = ele && ele.branchSettings && ele.branchSettings.saleMan ? ele.branchSettings.saleMan : [];
    const branches = ele && ele.branchSettings ? _.map(ele.branchSettings, (v) => {
      return v.branch;
    }) : [];

    this.setState({ branches });
  }

  checkApplyStatus = (serviceId, shopId, branch_no, card_no, apply_time) => {
    return new Promise((resolve, reject) => {
      appointmentService.checkApplyStatus(serviceId, shopId, branch_no, card_no, apply_time).then((result) => {
        if (_.isNil(result.data) || _.isEmpty(result.data)) {
          resolve({ applyNumStatus: false, dayBranchApplyStatus: false });
          return;
        }
        resolve(result.data);
      }, (error) => {
        reject({ applyNumStatus: false, dayBranchApplyStatus: false });
      });
    });
  }


  handleSubmit = () => {
    const selectServiceId = this.state.selectServiceId;
    const selectBranch = this.state.selectBranch;
    const selectTime = this.state.selectTime;
    const selectSaleMan = this.state.selectSaleMan;

    const shopId = this.props.location.query.shopId;
    const card_no = this.props.location.query.card_no;
    this.checkApplyStatus(selectServiceId, shopId, selectBranch.branch_no, card_no, selectTime).then((rs) => {
      // this.setState(rs);

      if (!selectServiceId) {
        Toast.info('请选择服务', 1);
      } else if (!selectBranch) {
        Toast.info('请选门店', 1);
      } else if (!selectTime) {
        Toast.info('请选择预约时间', 1);
      }
      else if (rs.dayBranchApplyStatus === false) {
        Toast.info('抱歉，您今天已在该门店提交预约', 1);
      } else if (rs.applyNumStatus === false) {
        Toast.info('抱歉，当前时间预约已满', 1);
      } else {
        const params = {
          service_id: selectServiceId,
          service_name: _.get(_.find(this.props.services, { _id: selectServiceId }), 'name', ''),
          branch_no: selectBranch.branch_no,
          branch_name: selectBranch.branch_name,
          apply_time: selectTime,
          sale_id: selectSaleMan.sale_id,
          sale_name: selectSaleMan.sale_name,
          shopId,
          card_no,
          status: '0', /* status:0->待处理,1->已完成,2->已取消*/
        };
        this.props.submitAppointment(params);
        this.props.history.push({pathname: '/AppointmentSuccess', query: params})
      }
    }, (error) => {
      // this.setState({ applyNumStatus: false, dayBranchApplyStatus: false });
      Toast.info('选项为空')
      console.log(error);
    });
  }


  goToAppointmentPage = () => {
    const shopId = this.props.location.query.shopId;
    const card_no = this.props.location.query.card_no;
    this.props.goToAppointmentPage(shopId, card_no);
  }

  onCloseMessage = () => {
    const shopId = this.props.location.query.shopId;
    const card_no = this.props.location.query.card_no;
    this.props.hideMessageModal(shopId, card_no);
  }

  showMessage = (msg) => {
    Toast.info(msg, 1);
  }

  showPopup = (timeSelectModalProps) => {
    Popup.show(
      <TimeSelectModal {...timeSelectModalProps} />,
      { animationType: 'slide-up', maskClosable: true },
    );
  }

  render() {
    console.log(this.state)
    const thiz = this;
    const branchSelectModalProps = {
      visiable: this.state.branchSelectModalVisiable,
      dataSource: this.state.branches,
      onOk(data) {
        thiz.setState({ selectBranch: data }, () => {
          const service = _.find(thiz.props.services, { _id: thiz.state.selectServiceId });
          const branchSetting = _.find(service.branchSettings || [], { branch_no: data.branch_no });
          thiz.setState({ branchSelectModalVisiable: false, branchSetting, selectTime: '' });
        });
      },
      onCancel() {
        thiz.setState({ branchSelectModalVisiable: false });
      },
    };

    const timeSelectModalProps = {
      visiable: this.state.timeSelectModalVisiable,
      dataSource: this.state.branchSetting,
      onOk(data) {
        thiz.setState({ timeSelectModalVisiable: false, selectTime: data });
        Popup.hide();
      },
      onCancel() {
        thiz.setState({ timeSelectModalVisiable: false });
        Popup.hide();
      },
    };


    const saleManSelectModalProps = {
      visiable: this.state.saleManSelectModalVisiable,
      dataSource: this.state.branchSetting && this.state.branchSetting.saleMan ? this.state.branchSetting.saleMan : [],
      onOk(data) {
        thiz.setState({ selectSaleMan: data, saleManSelectModalVisiable: false });
      },
      onCancel() {
        thiz.setState({ saleManSelectModalVisiable: false });
      },
    };

    return (
      <Container title="预约服务">
        <div className={styles.container}>
          <Helmet>
            <title>预约服务</title>
          </Helmet>

          <div className={styles.wrapper_container}>
            <div className={styles.title_h3}>请选择服务项目</div>
            <div className={styles['service-container']}>
              <Flex wrap="wrap" justify="start" align="start" >
                {this.props.services.map((item, index) => {
                  return (
                    <div
                      key={"qwer" + index}
                      className={classnames({
                        [styles['service-item']]: true,
                        [styles.active]: item.isChecked,
                      })}
                      onClick={this.handleServiceClick.bind(this, item)}
                    >
                      <img className={styles["service-image"]} src={require('../assets/new/pre_app.png')} />
                      <span className={styles["service-name"]}>{item.name}</span>
                    </div>
                  );
                })}
              </Flex>
            </div>
          </div>

           {/* 请选择服务项目 */}
           {/* <div className={styles.serviceItem}>
               <div className={styles.serviceTitle}>请选择服务项目</div>
               <div className={styles.serWrap}>
               {this.props.services.map((item, index) => {
                  return (
                    <div 
                    className={styles.serItem}
                    onClick={this.handleServiceClick.bind(this, item)}
                    >
                      <img src={require('../assets/new/pre_app.png')} alt='请选择服务项目'/>
                      <div className={styles.itemName}>护肤</div>
                    </div>
                  )
               })}
               </div>
           </div> */}
           {/* ----- */}
           <div className={styles.grey}></div>
          <div className={styles["other-items-container"]}>
            <div
              className={styles["other-item"]}
              onClick={!_.isEmpty(this.state.selectServiceId) ? this.handClickBranch : () => this.showMessage('请选择服务')}
            >
              <h5 className={styles["item-title"]}>请选择服务门店</h5>
              <span className={styles["options-desc"]}>
                {!_.isEmpty(this.state.selectBranch) ? this.state.selectBranch.branch_name : `共${this.state.branches.length}门店`}
              </span>
              <span className={styles["other-right-icon"]}>
                <Icon type="right" size="md" />
              </span>
            </div>

            <div
              className={styles["other-item"]}
              onClick={!_.isEmpty(this.state.selectBranch) ? this.showPopup.bind(this, timeSelectModalProps) : () => this.showMessage('选择服务时间')}
            >
              <h5 className={styles["item-title"]}>请选择服务时间</h5>
              <span className={styles["options-desc"]}>
                {!_.isEmpty(this.state.selectTime) ? this.state.selectTime : `选择服务时间`}
              </span>
              <span className={styles["other-right-icon"]}>
                <Icon type="right" size="md" />
              </span>
            </div>
            



            {/* 
              <div className={styles["other-item"]} 
              onClick={!_.isEmpty(this.state.selectBranch) ? this.handClickSaleMan : () => this.showMessage('请选择门店')}>
                <h5 className={styles["item-title"]}>请选择育婴师</h5>
                <span className={styles["options-desc"]}>
                {!_.isEmpty(this.state.selectSaleMan) && this.state.selectSaleMan.sale_name ? this.state.selectSaleMan.sale_name : `共${this.state.branchSetting && this.state.branchSetting.saleMan ? this.state.branchSetting.saleMan.length : 0}育婴师可选`}
                </span>
                <span className={styles["other-right-icon"]}>
                  <Icon type="right" size="md" />
                </span>
              </div>
            */}
            <div
              className={styles["other-item"]}
              onClick={!_.isEmpty(this.state.selectBranch) ? this.handClickSaleMan : () => this.showMessage('请选择门店')}
            >
              <h5 className={styles["item-title"]}>请选择服装顾问</h5>
              <span className={styles["options-desc"]}>
              {!_.isEmpty(this.state.selectSaleMan) && this.state.selectSaleMan.sale_name ? this.state.selectSaleMan.sale_name : `共${this.state.branchSetting && this.state.branchSetting.saleMan ? this.state.branchSetting.saleMan.length : 0}位化妆师可选`}
              </span>
              <span className={styles["other-right-icon"]}>
                <Icon type="right" size="md" />
              </span>
            </div>
          </div>

          <div className={styles["button-group"]}>
            <button className={styles["btn-submit"]} type="button" onClick={this.handleSubmit}>提交预约</button>
            <button className={styles["btn-preview"]} type="button" onClick={this.goToAppointmentPage}>预约记录</button>
          </div>

          <BranchSelectModal {...branchSelectModalProps} />
          {/* <TimeSelectModal {...timeSelectModalProps} /> */}
          <SaleManSelectModal {...saleManSelectModalProps} />
          {/* <Modal
            title="提示"
            transparent
            maskClosable={false}
            visible={this.props.submited}
            onClose={() => this.onCloseMessage()}
            footer={[{
              text: '确定',
              onPress: () => {
                this.onCloseMessage();
              },
            }]}
          >
            预约成功!
          </Modal> */}
        </div>
      </Container>
    );
  }
}


// connet传两个参数
export default connect((state) => {
  return {
    user: state.auth.currentUser,
    services: state.appointment.appointmentSetting,
    submited: state.appointment.submited,
    currentVip: state.appointment.currentVip,
    shopId: state.auth.currentUser.shop_no,
  };
},
  (dispatch) => {
    return {
      dispatch,
      fetchAppointmentSetting(shopId) {
        dispatch({ type: 'appointment/fetchAppointment', payload: { shopId } });
      },
      submitAppointment(params) {
        dispatch({ type: 'appointment/submitAppointment', payload: params });
      },
      hideMessageModal(shopId, card_no) {
        dispatch({ type: 'appointment/saveSubmited', payload: false });
        dispatch(routerRedux.push({ pathname: '/appointmentResult', query: { shopId, card_no } }));
      },
      goToAppointmentPage(shopId, card_no) {
        dispatch({ type: 'appointment/saveSubmited', payload: false });
        dispatch(routerRedux.push({ pathname: '/appointmentResult', query: { shopId, card_no } }));
      },
      fetchCurrentVip() {
        const { shopId, card_no } = this.props.location.query;
        dispatch({ type: 'appointment/saveCurrentVip', payload: { shopId, card_no } });
      },
    };
  },
)(createForm()(Appointment));
